package com.luoyi.util.ehr;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * 去除时间8个0的代码
 */
public class Replace0Date {

    /**
     * 数据库18表中的 CLUSTD  【数据】
     */
    private final static String tableDataStr = ResourceUtil.readStr("./text/test4/d.json", Charset.defaultCharset());

    /**
     * 数据库18表中的 CLUSTR   【字段名】
     */
    private final static String headFieldStr = ResourceUtil.readStr("./text/test4/r.json", Charset.defaultCharset());

    public static void main(String[] args) {
        execute();
    }

    private static void execute() {
        JSONArray headFields = JSON.parseArray(headFieldStr);
        JSONArray dataArray = JSON.parseArray(tableDataStr);

        // 准备表头数据
        Map<String, JSONObject> headFieldMap = new HashMap<>();
        for (int i = 0; i < headFields.size(); i++) {
            JSONObject item = headFields.getJSONObject(i);
            String infoType = item.getString("INFTY");
            JSONArray fields = item.getJSONArray("FIELD");
            for (int j = 0; j < fields.size(); j++) {
                JSONObject field = fields.getJSONObject(j);
                headFieldMap.put(infoType + "--" + field.getString("FIELD"), field);
            }
        }

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject jsonObject = dataArray.getJSONObject(i);
            String infoType = jsonObject.getString("INFTY");
            JSONArray infoTypeItemArray = jsonObject.getJSONArray("VALUE");
            for (int j = 0; j < infoTypeItemArray.size(); j++) {
                JSONObject valueItem = infoTypeItemArray.getJSONObject(j);
                HashSet<String> needReplaceKey = new HashSet<>();
                valueItem.forEach((key, value) -> {
                    if (!"00000000".equals(value.toString())) {
                        return;
                    }
                    String fieldKey = infoType + "--" + key;
                    JSONObject field = headFieldMap.get(fieldKey);
                    if (field == null) {
                        return;
                    }
                    String fType = field.getString("FTYPE");
                    if ("D".equals(fType)) {
                        needReplaceKey.add(key);
                    }
                });
                needReplaceKey.forEach(key -> {
                    valueItem.put(key, StrUtil.EMPTY);
                });
            }
            jsonObject.put("VALUE", infoTypeItemArray.toJSONString());
        }


        System.out.println(JSON.toJSONString(dataArray));
    }


}
